<template>
  <div class="margin-top">
    <!-- 搜索框 -->
    <el-input v-model="searchValue" placeholder="请输入用户名" style="width: 200px; margin-bottom: 10px;"></el-input>
    <el-button type="primary" size="small" @click="searchUser">搜索用户</el-button>

    <!-- 用户列表 -->
    <el-table :data="filteredUsers" style="width: 100%">
      <el-table-column prop="uid" label="用户id"></el-table-column>
      <el-table-column prop="uname" label="用户名称"></el-table-column>
      <el-table-column prop="upass" label="用户密码"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="hobby" label="爱好"></el-table-column>
      <el-table-column prop="address" label="联系地址"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="deleteUser(scope.row.uid)">删除</el-button>
          <el-button type="primary" size="small" @click="showResetPasswordDialog(scope.row.uid)">改密</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 重置密码对话框 -->
    <el-dialog :visible.sync="resetPasswordDialogVisible" title="重置密码">
      <el-form :model="resetPasswordForm" ref="resetPasswordForm" :rules="resetPasswordRules" label-width="100px">
        <el-form-item label="新密码" prop="upass">
          <el-input type="password" v-model="resetPasswordForm.upass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="resetPasswordForm.confirmPassword" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="resetPassword">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      searchValue: '',
      users: [],
      resetPasswordDialogVisible: false,
      resetPasswordForm: {
        userId: '',
        upass: '', // 使用 upass 作为新密码字段
        confirmPassword: ''
      },
      resetPasswordRules: {
        upass: [{
          required: true,
          message: '请输入新密码',
          trigger: 'blur'
        },
          {
            min: 6,
            message: '密码不能少于6位数',
            trigger: 'blur'
          }],
        confirmPassword: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          {
            validator: this.validateConfirmPassword,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.fetchUsers()
  },
  computed: {
    filteredUsers () {
      return this.users.filter(user => user.uname.toLowerCase().includes(this.searchValue.toLowerCase()))
    }
  },
  methods: {
    async fetchUsers () {
      try {
        const response = await axios.get('http://localhost:7070/api/superadmin/alluser')
        this.users = response.data
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },
    searchUser () {
      console.log('搜索用户：', this.searchValue)
    },
    deleteUser (uid) {
      this.$confirm('确认删除该用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:7070/api/superadmin/deleteuser/${uid}`)
            .then(() => {
              this.$message.success('删除用户成功！')
              this.fetchUsers()
            })
            .catch(error => {
              console.error('删除用户失败:', error)
              this.$message.error('删除用户失败！')
            })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    showResetPasswordDialog (id) {
      this.resetPasswordForm.userId = id
      this.resetPasswordDialogVisible = true
    },
    resetPassword () {
      // 首先验证确认密码与新密码是否一致
      if (this.resetPasswordForm.confirmPassword !== this.resetPasswordForm.upass) {
        this.$message.error('确认密码与新密码不一致')
        return
      }

      // 发送重置密码请求
      axios.put(`http://localhost:7070/api/superadmin/modifypass/${this.resetPasswordForm.userId}`, {
        uid: this.resetPasswordForm.userId,
        upass: this.resetPasswordForm.upass // 使用 Upass 作为新密码字段
      })
          .then(response => {
            // 修改这里的判断逻辑，根据响应状态码判断成功或失败
            if (response.status === 200) {
              this.$refs.resetPasswordForm.resetFields() // 重置表单
              this.resetPasswordDialogVisible = false // 关闭对话框
              this.$message.success('重置密码成功！') // 显示成功提示

              // 更新页面数据，重新获取用户列表等操作
              this.fetchUsers() // 重新获取用户列表数据
            } else {
              this.$message.error('重置密码失败：' + response.data) // 显示失败提示
            }
          })
          .catch(error => {
            console.error('重置密码失败:', error)
            this.$message.error('重置密码失败！')
          })
    },
    validateConfirmPassword (rule, value, callback) {
      if (value !== this.resetPasswordForm.upass) { // 验证确认密码与新密码是否一致
        callback(new Error('确认密码与新密码不一致'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style scoped>
.margin-top {
  margin-top: 1px;
}
</style>
